package actors

import (
	"sync"
	proto "xagent/proto/v1"
)

// TaskSchedulerImpl manages task scheduling and execution
type TaskSchedulerImpl struct {
	tasks    map[string]*proto.Task
	queue    []*proto.Task
	mutex    sync.RWMutex
	maxTasks int
}

// NewTaskSchedulerImpl creates a new task scheduler
func NewTaskSchedulerImpl() *TaskSchedulerImpl {
	return &TaskSchedulerImpl{
		tasks:    make(map[string]*proto.Task),
		queue:    make([]*proto.Task, 0),
		maxTasks: 10,
	}
}

// ScheduleTask adds a task to the scheduler
func (s *TaskSchedulerImpl) ScheduleTask(task *proto.Task, priority TaskPriority) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	s.tasks[task.Id] = task
	s.queue = append(s.queue, task)
}

// GetNextTask gets the next task to execute
func (s *TaskSchedulerImpl) GetNextTask() *proto.Task {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	if len(s.queue) == 0 {
		return nil
	}

	task := s.queue[0]
	s.queue = s.queue[1:]
	delete(s.tasks, task.Id)
	return task
}

// HasTasks checks if there are any tasks in the queue
func (s *TaskSchedulerImpl) HasTasks() bool {
	s.mutex.RLock()
	defer s.mutex.RUnlock()
	return len(s.queue) > 0
}

// GetTaskCount returns the number of tasks in the queue
func (s *TaskSchedulerImpl) GetTaskCount() int {
	s.mutex.RLock()
	defer s.mutex.RUnlock()
	return len(s.queue)
}

// GetTask gets a task by ID
func (s *TaskSchedulerImpl) GetTask(id string) (*proto.Task, bool) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()
	task, ok := s.tasks[id]
	return task, ok
}

// RemoveTask removes a task from the scheduler
func (s *TaskSchedulerImpl) RemoveTask(id string) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	delete(s.tasks, id)
	for i, task := range s.queue {
		if task.Id == id {
			s.queue = append(s.queue[:i], s.queue[i+1:]...)
			break
		}
	}
}
